//
//  RemembeAccountLoginView.m
//  QRMaster
//
//  Created by myApple on 16/3/1.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "RemembeAccountLoginView.h"
#import "AllConstants.h"
#import "LineView.h"
#import "validateInputValue.h"
#import "UIImageView+WebCache.h"
#import "UserInfoLogic.h"
#import "userInfoModel.h"

@interface RemembeAccountLoginView()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate,UIActionSheetDelegate>
{
    UIButton * languageBtn;
    UIImageView * headerImageView;
    UILabel * accountLabel;//账号
    UITextField * passWordTextField;
    NSArray * moreDataArray;
    LineView * passWordLine;
    UIButton * seePWDBtn;
    UIButton * moreBtn;
    UIButton * LoginBtn;
    
    UITableView * MoreTableView;
    UIView * backView;
    BOOL passWordFlag;
}

@end

@implementation RemembeAccountLoginView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        passWordFlag = NO;
        moreDataArray = @[NSLocalizedString(@"registBtn",nil),NSLocalizedString(@"changeAccount",nil)];
        [self prepareView];
        [self prepareMoreView];
        [self getDataFromDisk];
    }
    return self;
}

-(void)getDataFromDisk
{
    __block userInfoModel *userModel = [[userInfoModel alloc]init];
    UserInfoLogic *userLogic = [[UserInfoLogic alloc]init];
    
    [userLogic queryUserInfo:^(userInfoModel *myUserModel)
     {
         userModel = myUserModel;
     }
     ];
    
   [headerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERURL,userModel.headUrl]] placeholderImage:[UIImage imageNamed:@"96人像"]];
}


-(void)prepareView
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    
    float ScreenWidth = self.frame.size.width;
    float ScreenHeight = self.frame.size.height;
    float x = ScreenWidth / 2.0 - 40;
    float y = ScreenHeight / 2.0 - 191;
    float width = 80;
    float height = 80;
    //头像
    headerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    headerImageView.layer.cornerRadius = 40;
    headerImageView.layer.masksToBounds = YES;
    [self addSubview:headerImageView];
    
    x = 0;
    y += height + 14;
    width = ScreenWidth;
    height = 20;
    
    accountLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    accountLabel.font = [UIFont systemFontOfSize:14.0];
    accountLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:accountLabel];
    
    
    //密码
    y += height + 17;
    x = 72;
    width = ScreenWidth - x - 20;
    height = 39;
    passWordTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    passWordTextField.secureTextEntry = YES;
    passWordTextField.placeholder = NSLocalizedString(@"passPromt", nil);
    passWordTextField.delegate = self;
    passWordTextField.font = [UIFont systemFontOfSize:13.0];
    passWordTextField.borderStyle = UITextBorderStyleNone;
    passWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:passWordTextField];
    passWordLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 1)];
    passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self addSubview:passWordLine];
    
    UIImageView * passWordView = [[UIImageView alloc]initWithFrame:CGRectMake(22, y+10, 14, 18)];
    UIImage * passWordImg = [UIImage imageNamed:@"loginPWDImage"];
    passWordView.image = passWordImg;
    [self addSubview:passWordView];
//    passWordTextField.leftView = passWordView;
//    passWordTextField.leftViewMode = UITextFieldViewModeAlways;
    
//    UILabel * passWordLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, y + 10, 100, 20)];
//    passWordLabel.text = NSLocalizedString(@"passWord", nil);
//    passWordLabel.font = [UIFont systemFontOfSize:13.0];
//    [self addSubview:passWordLabel];
    
    //小眼睛
    UIImageView * oldSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    passWordTextField.rightViewMode = UITextFieldViewModeAlways;
    passWordTextField.rightView = oldSeeImgView;
    oldSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * oldSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seePwd)];
    [oldSeeImgView addGestureRecognizer:oldSeeTap];
    seePWDBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    seePWDBtn.frame = CGRectMake(18, 14, 16, 12);
    seePWDBtn.selected = NO;
    seePWDBtn.userInteractionEnabled = NO;
    [seePWDBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [seePWDBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [oldSeeImgView addSubview:seePWDBtn];
    
    
    x = 20;
    y += height + 26;
    width = ScreenWidth - x - 20;
    height = 48;
    LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    LoginBtn.frame = CGRectMake(x, y, width, height);
    [LoginBtn setTitleColor:UIColorFromRGBAndA(0xffffff, 0.5) forState:0];
    [LoginBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc234, 0.5)];
    [LoginBtn setTitle:NSLocalizedString(@"loginBtn", nil) forState:0];
    LoginBtn.layer.cornerRadius = 5;
    LoginBtn.enabled = NO;
    LoginBtn.titleLabel.font = [UIFont systemFontOfSize:19.0];
    [LoginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:LoginBtn];
    
    x = UI_SCREEN_WIDTH - 142;
    width = 120;
    height = 39;
    y += height + 10;
    UIButton * forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBtn.frame = CGRectMake(x, y, width, height);
    [forgetBtn setTitle:NSLocalizedString(@"forgetBtn", @"忘记密码") forState:0];
    forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [forgetBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [forgetBtn setBackgroundColor:[UIColor clearColor]];
    [forgetBtn addTarget:self action:@selector(forgetClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:forgetBtn];
    
    
    //更多
    x = ScreenWidth / 2.0 - 20;
    width = 40;
    y = ScreenHeight - 60;
    height = 20;
    moreBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    moreBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [moreBtn setTitle:NSLocalizedString(@"more", nil) forState:0];
    [moreBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [moreBtn addTarget:self action:@selector(moreChoose) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:moreBtn];
}

#pragma mark ------------ uitextfileddelegate
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    passWordFlag = NO;
    [self canTapOfRegist];
    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (newString.length > 0) {
        passWordFlag = YES;
    }
    else
    {
        passWordFlag = NO;
    }
    [self canTapOfRegist];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    passWordLine.backgroundColor = UIColorFromRGB(0x7dc234);
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
}


#pragma mark ------------- 准备“更多”的view
-(void)prepareMoreView
{
    backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    backView.hidden = YES;
    backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
//    [[UIApplication sharedApplication].keyWindow addSubview:backView];
    [self addSubview:backView];
    
    UITapGestureRecognizer * tapBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenBackView)];
    tapBackView.delegate = self;
    [backView addGestureRecognizer:tapBackView];
    
    MoreTableView = [[UITableView alloc]initWithFrame:CGRectMake(40, UI_SCREEN_HEIGHT / 2.0 - 60, UI_SCREEN_WIDTH - 80, moreDataArray.count * 40)];
    MoreTableView.delegate = self;
    MoreTableView.dataSource = self;
    [backView addSubview:MoreTableView];
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    if ([NSStringFromClass([touch.view class]) isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return  YES;
}


#pragma mark ----------uitableviewdelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return moreDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellID = @"cellId";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.textLabel.text = moreDataArray[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self hiddenBackView];
    switch (indexPath.row) {
        case 0:
            [self resigstClick];
            break;
        case 1:
            [self changeAccount];
            break;
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark --------显示个人信息
-(void)showUserInfo
{
    accountLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userMobile"];
}


#pragma mark --------- 查看密码
-(void)seePwd
{
    seePWDBtn.selected = !seePWDBtn.selected;
    if (seePWDBtn.selected) {
        passWordTextField.secureTextEntry = NO;
    }
    else
    {
        passWordTextField.secureTextEntry = YES;
    }
}

#pragma mark ----------更多选择
-(void)moreChoose
{
//    backView.hidden = NO;
    UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"registBtn",nil),NSLocalizedString(@"changeAccount",nil), nil];
    [actionSheet showInView:self];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
          [self resigstClick];
    }
    else if (buttonIndex == 1)
    {
        [self changeAccount];
    }
}

#pragma mark -------- 点击背景
-(void)hiddenBackView
{
    backView.hidden = YES;
}

#pragma mark ---------切换账号
-(void)changeAccount
{
    if (_delegate && [_delegate respondsToSelector:@selector(changeAccountRem)]) {
        [_delegate changeAccountRem];
    }
}


-(void)forgetClick
{
    if (_delegate && [_delegate respondsToSelector:@selector(ForgetPassWordRem)]) {
        [_delegate ForgetPassWordRem];
    }
}

-(void)resigstClick
{
    if (_delegate && [_delegate respondsToSelector:@selector(ResgsitRem)]) {
        [_delegate ResgsitRem];
    }
}


-(void)loginClick:(UIButton *)btn
{
    [self endEditing:YES];
    [passWordTextField resignFirstResponder];
    if (![validateInputValue validateStringIsNull:accountLabel.text])
    {
        if (![validateInputValue validateEmail:accountLabel.text] && ![validateInputValue isPureNumandCharacters:accountLabel.text])
        {
            
            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAccount", nil)];
        return;
    }
    
    if (![validateInputValue validatePassword:passWordTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"loginingPromt", nil)];
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(remWithLogin:PassWord:)]) {
        [_delegate remWithLogin:[[NSUserDefaults standardUserDefaults] objectForKey:@"userMobile"] PassWord:passWordTextField.text];
    }
}

#pragma mark ----------- 判断注册按钮是否能够点击
-(void)canTapOfRegist
{
    if (passWordFlag) {
        [self loginBtnEnable];
    }
    else
    {
        [self loginBtnDisenable];
    }
}


#pragma mark ----------注册按钮点击和不可以点击的两种状态
-(void)loginBtnEnable
{
    [LoginBtn setBackgroundColor:UIColorFromRGB(0x7cd234)];
    [LoginBtn setTitleColor:UIColorFromRGB(0xffffff) forState:0];
    LoginBtn.enabled = YES;
}

-(void)loginBtnDisenable
{
    [LoginBtn setBackgroundColor:UIColorFromRGBAndA(0x7cd234, 0.5)];
    [LoginBtn setTitleColor:UIColorFromRGBAndA(0xffffff,0.5) forState:0];
    LoginBtn.enabled = NO;
}


-(void)hiddenKeyboard
{
    [passWordTextField resignFirstResponder];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
//    [backView removeFromSuperview];
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
